import {
  HTTP
} from '../../utils/http'
import Wxml2Canvas from '../../miniprogram_npm/wxml2canvas/index';
import Toast from '@vant/weapp/toast/toast';
let http = new HTTP()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    myGridShow: false,
    isShowSet: false,
    myPictureStyleShow: false,
    myTextCorrelationShow: false,
    myPictureCorrelationShow: false,
    myReferencePictureShow: false,
    shieldingWordsShow: false,
    textFontShow: false,
    fileList: [],
    fileListModel: [],
    // 关键字textarea最高高度和最小高度
    autosize: {
      maxHeight: '424rpx',
      minHeight: '424rpx'
    },
    autosizeTextContent: {
      maxHeight: '124rpx',
      minHeight: '124rpx'
    },
    // 使用图片switch选中标识
    usePicturesChecked: false,
    // 表单数据json
    formData: {
      keyWord: "", // 关键字
      pictureScale: null, // 生成图片比例(废弃)
      pictureStyle: null, // 图片风格
      textCorrelation: 7.5, //文本相关性
      usePictures: false, //使用图片
      referencePicture: null, //参考图
      pictureCorrelation: 0.7, //图片相关性
      shieldingWords: null, //屏蔽词
      name: "盒子名称",
      modelImg: []
    },
    // 字体字典
    textFontDict: [{
        id: 1,
        chinese: "灵图闪创"
      },
      {
        id: 2,
        chinese: "灵图闪创"
      }
    ],
    // 图片比例数组
    pictureScaleList: [{
      resolution: '512*512',
      proportion: '1:1',
      width: '162rpx',
      height: '162rpx'
    }, {
      resolution: '512*768',
      proportion: '2:3',
      width: '108rpx',
      height: '162rpx'
    }, {
      resolution: '768*512',
      proportion: '3:2',
      width: '162rpx',
      height: '108rpx'
    }],
    // 图片风格
    pictureStyleList: [],
    boxId: null,
    isBuild: false, // todo 测试完成后需要改为false
    buildData: {
      imgSrc: null
    },
    stv: {
      offsetX: 0,
      offsetY: 0,
      zoom: false, //是否缩放状态
      distance: 0, //两指距离
      scale: 1, //缩放倍数
    },
    textIni: {
      textFont: null, //文字字体
      textContent: null, //文字内容
      textColor: "#000000", //文字颜色
      textBorder: false, //显示文字描边
      textBorderColor: "#000000" //文字描边颜色
    },
    activeFontId: null,
    activeFont: null,
    editTextContentShow: false,
    tempTextContent: null,
    textColorShow: false,
    textBorderColorShow: false
  },
  textBorderColorPickColor(e) {
    this.setData({
      "textIni.textBorderColor": e.detail.color
    })
  },
  onTextBorderColor(e) {
    this.setData({
      textBorderColorShow: true
    })
  },
  textColorPickColor(e) {
    this.setData({
      "textIni.textColor": e.detail.color
    })
  },
  onTextColor(e) {
    this.setData({
      textColorShow: true
    })
  },
  onDoneTextContent(e) {
    this.setData({
      "textIni.textContent": this.data.tempTextContent
    })
  },
  onTextContentChange(e) {
    this.setData({
      tempTextContent: e.detail
    })
  },
  onEditTextContent(e) {
    this.setData({
      editTextContentShow: true
    })
  },
  onClickTextFont(e) {
    let textFont = e.currentTarget.dataset.textfont;
    this.setData({
      activeFontId: textFont.id,
      activeFont: textFont
    })
  },
  onDoneTextFont(e) {
    this.setData({
      "textIni.textFont": this.data.activeFont.chinese
    })
  },
  onSelectTextFont(e) {
    this.setData({
      textFontShow: true
    })
  },
  onShowTextBorder(e) {
    this.setData({
      "textIni.textBorder": !this.data.textIni.textBorder
    })
  },
  onShowSet(e) {
    this.setData({
      isShowSet: !this.data.isShowSet
    })
  },
  //保存图片到相册，提示保存成功
  savePhoto(url) {
    let that = this
    wx.downloadFile({
      url: url,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            wx.showToast({
              title: '保存成功',
              icon: "success",
              duration: 1000
            })
          }
        })
      }
    })
  },
  finish(e) {
    // 先上传文件再接口调用
    let that = this
    wx.showLoading({
      title: '表情最终提交中',
      mask:true
    })
    this.drawCanvas((url)=>{
      http.uploadFile({
        url: '/ai/draw/box/upload/pic',
        filePath: url,
        name: 'file', //后端接收图片的字段名
        success(res) {
          res = JSON.parse(res)
          if (res.code === '0') {
            const data = res.data
            that.setData({
              "buildData.imgSrc": data
            })
            http.request({
              url: '/ai/draw/picture/create/finish',
              method: "POST",
              data: {
                "url": that.data.buildData.imgSrc,
                "boxId": that.data.boxId,
                "description": that.data.formData.keyWord
              },
              success: (res) => {
                wx.hideLoading()
                if (res.code === "0") {
                  wx.redirectTo({
                    url: '/pages/box-detail/box-detail?id=' + that.data.boxId,
                  })
                }
              },
              error: ()=>{
                wx.hideLoading()
              },
              fail:()=>{
                wx.hideLoading()
              }
            })
          } else {
            wx.hideLoading()
            Toast.fail({
              message: res.msg,
              context: that
            });
          }
        },
        error(err) {
          Toast.fail({
            message: '图片上传失败!' + err,
            context: that
          });
        }
      })
    })
    
  },
  onBuildFalse(e) {
    this.setData({
      isBuild: false
    })
  },
  onKeyWordChange(e) {
    this.setData({
      "formData.keyWord": e.detail
    })
  },
  // 点击生成盒子
  onCreateBox(e) {
    wx.showLoading({
      title: '表情生成中',
      mask:true
    })
    let formData = this.data.formData
    let data = {
      /**
       * 盒子id
       */
      boxId: this.data.boxId,
      /**
       * 盒子描述
       */
      "description": formData.keyWord,
      /**
       * 文本相关性 0-20，默认7.5
       */
      "guidance": formData.textCorrelation,
      /**
       * 生成表情包高
       */
      "high": 512,
      /**
       * 生成表情包宽
       */
      "width": 512,
      /**
       * 参考图url
       */
      "initImageUrl": formData.referencePicture ? formData.referencePicture : (formData.modelImg ? formData.modelImg[0] : null),
      /**
       * 是否使用图片 0-未使用 1-使用
       */
      "isUsedImage": formData.usePictures ? 1 : 0,
      /**
       * 图像变化强度，0-1，默认0.7
       */
      "strength": formData.pictureCorrelation,
      /**
       * 风格-中文
       */
      "model": formData.pictureStyle
    }
    http.request({
      url: '/ai/draw/picture/build',
      method: "POST",
      data: data,
      success: (res) => {
        wx.hideLoading()
        this.setData({
          "buildData.imgSrc": res.data,
          "isBuild": true,
        })
      },
      error: ()=>{
        wx.hideLoading()
      },
      fail:()=>{
        wx.hideLoading()
      }
    })
  },
  onDeleteModelImg(e) {
    this.data.fileListModel.splice(e.currentTarget.dataset.imageIndex, 1);
    this.setData({
      fileListModel: this.data.fileListModel
    })
  },
  onShieldingWords(e) {
    this.setData({
      shieldingWordsShow: true
    })
  },
  onShieldingWordsDone(e) {
    this.setData({
      "formData.shieldingWords": e.detail.value
    })
  },
  onMyTextCorrelation(e) {
    this.setData({
      myTextCorrelationShow: true
    })
  },
  onMyTextCorrelatiDone(e) {
    if (e.detail) {
      this.setData({
        "formData.textCorrelation": e.detail
      })
    }
  },
  onMyPictureCorrelation(e) {
    this.setData({
      myPictureCorrelationShow: true
    })
  },
  onMyPictureCorrelationDone(e) {
    if (e.detail) {
      this.setData({
        myPictureCorrelationShow: false,
        "formData.pictureCorrelation": e.detail
      })
    }
  },
  onUsePicturesChange(e) {
    this.setData({
      "formData.usePictures": !this.data.formData.usePictures
    })
  },
  onMyGrid(e) {
    this.setData({
      myGridShow: true
    })
  },
  myGridOnDone(e) {
    this.setData({
      myGridShow: false,
      'formData.pictureScale': e.detail.value
    })
  },
  onMyReferencePicture(e) {
    this.setData({
      myReferencePictureShow: true
    })
  },
  onMyReferencePictureDone(e) {
    this.setData({
      myReferencePictureShow: false,
      'formData.referencePicture': e.detail
    })
  },
  onMyPictureStyle() {
    this.setData({
      myPictureStyleShow: true
    })
  },
  myPictureStyleOnDone(e) {
    this.setData({
      myPictureStyleShow: false,
      'formData.pictureStyle': e.detail.value.chinese,
      'formData.styleId': e.detail.value.id
    })
  },
  // 参考图上传
  afterRead(e) {
    let that = this
    http.uploadFile({
      url: '/ai/draw/box/upload/pic',
      filePath: e.detail.file.url,
      name: 'file', //后端接收图片的字段名
      success(res) {
        res = JSON.parse(res)
        if (res.code === '0') {
          const data = res.data
          that.setData({
            fileList: [{
              url: data
            }]
          })
          that.setData({
            "formData.referencePicture": data
          })
        } else {
          Toast.fail({
            message: res.msg,
            context: that
          });
        }
      },
      error(err) {
        Toast.fail({
          message: '图片上传失败!' + err,
          context: that
        });
      }
    })


  },
  // 模型图上传
  afterReadModel(e) {
    let that = this
    http.uploadFile({
      url: '/ai/draw/box/upload/pic',
      filePath: e.detail.file.url,
      name: 'file', //后端接收图片的字段名
      success(res) {
        res = JSON.parse(res)
        if (res.code === '0') {
          const data = res.data
          that.data.fileListModel.push({
            url: data
          })
          that.data.formData.modelImg.push(data)
          that.setData({
            "formData.modelImg": that.data.formData.modelImg,
            fileListModel: that.data.fileListModel
          })
        } else {
          Toast.fail({
            message: res.msg,
            context: that
          });
        }
      },
      error(err) {
        Toast.fail({
          message: '图片上传失败!' + err,
          context: that
        });
      }
    })


  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      boxId: options.boxId
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      isBuild: false
    })
    http.request({
      url: '/ai/draw/dict/get/list',
      method: "GET",
      data: {
        type: 0
      },
      success: (res) => {
        let data = res.data;
        this.setData({
          pictureStyleList: data
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 触摸开始
  touchstartCallback: function (e) {
    if (e.touches.length === 1) {
      let {
        clientX,
        clientY
      } = e.touches[0];
      this.startX = clientX;
      this.startY = clientY;
      this.touchStartEvent = e.touches;
    } else {
      let xMove = e.touches[1].clientX - e.touches[0].clientX;
      let yMove = e.touches[1].clientY - e.touches[0].clientY;
      let distance = Math.sqrt(xMove * xMove + yMove * yMove);
      this.setData({
        'stv.distance': distance,
        'stv.zoom': true, //缩放状态
      })
    }
  },
  // 触摸移动中
  touchmoveCallback: function (e) {
    //console.log('touchmoveCallback');
    //console.log(e);

    if (e.touches.length === 1) {
      // 单指移动
      if (this.data.stv.zoom) {
        // 缩放状态，不处理单指
        return;
      }
      let {
        clientX,
        clientY
      } = e.touches[0];
      let offsetX = clientX - this.startX;
      let offsetY = clientY - this.startY;
      this.startX = clientX;
      this.startY = clientY;
      let {
        stv
      } = this.data;
      stv.offsetX += offsetX;
      stv.offsetY += offsetY;
      stv.offsetLeftX = -stv.offsetX;
      stv.offsetLeftY = -stv.offsetLeftY;
      this.setData({
        stv: stv
      });
    } else {
      // 双指缩放
      let xMove = e.touches[1].clientX - e.touches[0].clientX;
      let yMove = e.touches[1].clientY - e.touches[0].clientY;
      let distance = Math.sqrt(xMove * xMove + yMove * yMove);

      let distanceDiff = distance - this.data.stv.distance;
      let newScale = this.data.stv.scale + 0.005 * distanceDiff;

      this.setData({
        'stv.distance': distance,
        'stv.scale': newScale,
      })
    }
  },
  // 触摸结束
  touchendCallback: function (e) {
    if (e.touches.length === 0) {
      this.setData({
        'stv.zoom': false, //重置缩放状态
      })
    }
  },
  draw(success) {
    let that = this
    
    //创建wxml2canvas对象
    let drawImage = new Wxml2Canvas({
      element: 'share', // canvas节点的id,
      obj: that, // 在组件中使用时，需要传入当前组件的this
      width: 686, // 宽高
      height: 686,
      background: 'transparent', // 默认背景色
      progress(percent) { // 绘制进度
      },
      finish(url) {
        // that.savePhoto(url)
        success&&success(url)
      },
      error(res) {
        // uni.hideLoading()
        // 画失败的原因
      }
    }, this);
    let data = {
      //直接获取wxml数据
      list: [{
        type: 'wxml',
        class: '.draw_canvas',
        limit: '.express-img',
        x: 0,
        y: 0
      }]
    }
    //传入数据，画制canvas图片
    drawImage.draw(data, this);
  },
  drawCanvas(success) {
    const query = wx.createSelectorQuery().in(this);
    query.select('#express-img').fields({
      size: true,
      scrollOffset: true
    }, data => {
      let width = data.width;
      let height = data.height;
      this.width = width;
      this.height = height;
      setTimeout(() => {
        this.draw(success)
      }, 1500);
    }).exec();
  }
})